package com.rockcent.mall.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.common.utils.RDateUtils;
import com.rockcent.helper.CategoryHelper;
import com.rockcent.mall.Prop;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.GiftPacketHelper;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.*;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.QRCodeHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantGiftPacketSrv;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by DK on 16/10/8.
 * 礼包管理
 */
@RestController
public class MerchantGiftPacketController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MerchantGiftPacketController.class);

    @Autowired
    private Prop prop;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private QRCodeHelper qrCodeHelper;

    @Autowired
    private GiftPacketHelper giftPacketHelper;

    @Autowired
    private CategoryHelper categoryHelper;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private MarketMerchantGiftPacketRepository marketMerchantGiftPacketRepository;

    @Autowired
    private MerchantProductCategoriesRepository merchantProductCategoriesRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private MerchantGiftPacketRepository merchantGiftPacketRepository;

    @Autowired
    private MerchantGiftPacketProductRepository merchantGiftPacketProductRepository;

    @Autowired
    private MerchantGiftPacketCouponRepository merchantGiftPacketCouponRepository;

    @Autowired
    private MallOrderRepository mallOrderRepository;

    @Autowired
    private MerchantGiftPacketSrv merchantGiftPacketSrvImpl;

    @Autowired
    private MarketMerchantCooperationRepository marketMerchantCooperationRepository;

    /**
     * @api {get} /merchant/gift/packet/page 产品礼包 分页
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=ALL("全部状态"), S1_DRAFTED("草稿"), S2_SELLING("进行中"), S3_UNLOAD("已下架"), S4_SOLDOUT("已售完"), S5_FINISHED("已结束"), S6_UNSTART("未开始")} status 礼包状态 <code>必须参数</code> 默认 ALL
     * @apiParam  {String} keyword 礼包名称/编号
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Date} dateEnabled 礼包开始时间
     * @apiSuccess {Date} dateDisabled 礼包结束时间
     * @apiSuccess {Long} marketPacketId 分销礼包唯一的识别码
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {Boolean} isRecommend 是否共享营销
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {String} saleCount 售出数
     * @apiSuccess {String} verifiedCount 核销数
     * @apiSuccess {String} viewCount 访问数
     * @apiSuccess {String} cAccessUrl C端访问链接
     * @apiSuccess {String=S1_DRAFTED("草稿"), S2_SELLING("进行中"), S3_UNLOAD("已下架"), S4_SOLDOUT("已售完"), S5_FINISHED("已结束"), S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *                "id" : 23,
     *                "name" : "组合礼包",
     *                "dateCreated" : "2016-07-22 10:49:28",
     *                "lastUpdated" : "2016-07-22 10:49:28",
     *                "dateEnabled" : "2016-07-22 10:49:28",
     *                "dateDisabled" : "2016-07-22 10:49:28",
     *                "marketPacketId" : 343,
     *                "coverUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "cAccessUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "intro" : "礼包介绍",
     *                "shareFee" : 21,
     *                "basePrice" : 231,
     *                "sellPrice" : 222,
     *                "isRecommend" : true,
     *                "merchantId" : 2,
     *                "mallId" : 1,
     *                "status" : "S2_SELLING",
     *                "saleCount" : "111",
     *                "verifiedCount" : "12",
     *                "viewCount" : "312"
     *            },
     *            .......
     *     ]
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_PAGE, method = RequestMethod.GET)
    public JsonResult giftPacketPage(HttpServletRequest request, GiftPacketDto giftPacketDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            PageResult<GiftPacketDto> pageResult = merchantGiftPacketRepository.findGiftPacketPage(userInfoDto.merchant.getId(), giftPacketDto.getStatus(), giftPacketDto.getKeyword(), this.getPage(giftPacketDto.getPageNo(), giftPacketDto.getPageSize()));
            pageResult.data.stream().map(giftPacket -> {
                Long saleCount = 0L;
                Long verifiedCount = 0L;
                List<MallOrder> mallOrderList = mallOrderRepository.findByGiftIdAndMallId(giftPacket.getId(), giftPacket.getMallId());
                for (MallOrder mallOrder : mallOrderList) {
                    if (MallOrderStatus.FINISHED == mallOrder.getStatus()) {
                        verifiedCount++;
                    }
                    if (MallOrderStatus.PAYED == mallOrder.getStatus()) {
                        saleCount++;
                    }
                }
                giftPacket.setSaleCount(saleCount);
                giftPacket.setVerifiedCount(verifiedCount);
                return giftPacket;
            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MERCHANT_GIFT_PACKET_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/gift/packet/delete 产品礼包 删除礼包(逻辑删除)
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {List} packetIds 礼包ID
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1".
     *     "desc" : "成功"
     * }
     *
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_DELETE, method = RequestMethod.PUT)
    public JsonResult giftPacketDelete(HttpServletRequest request, @RequestBody GiftPacketDto giftPacketDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (giftPacketDto.getPacketIds().size() == 0) {
                jsonResult.remind("礼包ID 不能为空",log);
                return;
            }
            List<MerchantGiftPacket> merchantGiftPacket = merchantGiftPacketRepository.findByMerchantIdAndIdIn(userInfoDto.merchant.getId(), giftPacketDto.getPacketIds());
            if (merchantGiftPacket.size() == 0) {
                jsonResult.remind("删除的礼包不存在",log);
                return;
            }
            merchantGiftPacket.forEach(giftPacket -> {
                giftPacket.setIsDelete(Whether.YES);
                merchantGiftPacketRepository.save(giftPacket);
                //删除被分销的礼包
                merchantGiftPacketSrvImpl.updateMarketGiftPacket(giftPacket.getId(), null, Whether.YES);
            });
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/gift/packet/stop 产品礼包 停止礼包
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {List} packetIds 礼包ID
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1".
     *     "desc" : "成功"
     * }
     *
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_STOP, method = RequestMethod.PUT)
    public JsonResult giftPacketStop(HttpServletRequest request, @RequestBody GiftPacketDto giftPacketDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (giftPacketDto.getPacketIds().size() == 0) {
                jsonResult.remind("礼包ID 不能为空",log);
                return;
            }
            List<MerchantGiftPacket> merchantGiftPacket = merchantGiftPacketRepository.findByMerchantIdAndIdIn(userInfoDto.merchant.getId(), giftPacketDto.getPacketIds());
            if (merchantGiftPacket.size() == 0) {
                jsonResult.remind("停止的礼包不存在", log);
                return;
            }
            merchantGiftPacket.forEach(giftPacket -> {
                giftPacket.setStatus(GiftPacketStatus.S5_FINISHED);
                merchantGiftPacketRepository.save(giftPacket);
                //停止被分销的礼包
                merchantGiftPacketSrvImpl.updateMarketGiftPacket(giftPacket.getId(), GiftPacketStatus.S5_FINISHED, null);
            });

        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/gift/packet/info 产品礼包 详情
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必须参数</code> 礼包ID
     * @apiParam {String} giftPacketInfoLink 礼包市场 我要销售 入口传link, 礼包管理  编辑 入口传空
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Date} dateEnabled 礼包开始时间
     * @apiSuccess {Date} dateDisabled 礼包结束时间
     * @apiSuccess {String} marketPacketId 分销礼包唯一的识别码
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {Boolean} isRecommend 是否共享营销
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {String=S1_DRAFTED("草稿"), S2_SELLING("已上架"), S3_UNLOAD("已下架"), S4_SOLDOUT("已售完"), S5_FINISHED("已结束"), S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccess {Long} masterPacketProduct_productId 主产品
     * @apiSuccess {String} masterPacketProduct_name 主产品名称
     * @apiSuccess {String} masterPacketProduct_logoUrl 产品图片路径
     * @apiSuccess {String} masterPacketProduct_merchantName 主产品商家名称
     * @apiSuccess {BigDecimal} masterPacketProduct_sellPrice 主产品售价
     * @apiSuccess {BigDecimal} masterPacketProduct_packetPrice 主产品新售价
     * @apiSuccess {Long} masterPacketProduct_quantity 主产品库存
     * @apiSuccess {Long} masterPacketProduct_useNumber 主产品适用数量
     * @apiSuccess {BigDecimal} masterPacketProduct_resellFee 主产品佣金
     * @apiSuccess {Long} masterPacketProduct_marketId 主产品供应商产品ID
     * @apiSuccess {Long} masterPacketProduct_marketMerchantId 主产品供应商ID
     *
     * @apiSuccess {Long} collocationPacketProductList_productId 搭配产品
     * @apiSuccess {String} collocationPacketProductList_name 搭配产品名称
     * @apiSuccess {String} collocationPacketProductList_logoUrl 产品图片路径
     * @apiSuccess {String} collocationPacketProductList_merchantName 搭配产品商家名称
     * @apiSuccess {BigDecimal} collocationPacketProductList_sellPrice 搭配产品售价
     * @apiSuccess {BigDecimal} collocationPacketProductList_packetPrice 主产品新售价
     * @apiSuccess {Long} collocationPacketProductList_quantity 搭配产品库存
     * @apiSuccess {Long} collocationPacketProductList_useNumber 搭配产品使用数量
     * @apiSuccess {BigDecimal} collocationPacketProductList_resellFee 搭配产品佣金
     * @apiSuccess {Long} collocationPacketProductList_marketId 搭配产品供应商产品ID
     * @apiSuccess {Long} collocationPacketProductList_marketMerchantId 搭配产品供应商ID
     *
     * @apiSuccess {Long} merchantPacketCouponList_couponId 卡卷id
     * @apiSuccess {String} merchantPacketCouponList_name 卡卷
     * @apiSuccess {String=ALL_STORE("所有门店"), ALL_PRODUCT("所有产品"), PART_STORE("指定门店"), PART_PRODUCT("PART_PRODUCT")} merchantPacketCouponList_useScope 卡卷适用范围
     * @apiSuccess {String=VOUCHERS("抵用券"), DISCOUNT("折扣券")} merchantPacketCouponList_type 卡卷
     * @apiSuccess {String} merchantPacketCouponList_merchantName 卡卷商家名称
     * @apiSuccess {Long} merchantPacketCouponList_leaveTotal 卡卷库存
     * @apiSuccess {Long} merchantPacketCouponList_useNumber 使用卡卷数量
     * @apiSuccess {String} merchantPacketCouponList_introduction 卡卷简介
     * @apiSuccess {String} merchantPacketCouponList_logoUrl 卡卷图片路径
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *               "id" : 23,
     *                "name" : "组合礼包",
     *                "dateCreated" : "2016-07-22 10:49:28",
     *                "lastUpdated" : "2016-07-22 10:49:28",
     *                "dateEnabled" : "2016-07-22 10:49:28",
     *                "dateDisabled" : "2016-07-22 10:49:28",
     *                "marketPacketId" : 343,
     *                "coverUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "intro" : "礼包介绍",
     *                "shareFee" : 21,
     *                "basePrice" : 231,
     *                "sellPrice" : 222,
     *                "isRecommend" : true,
     *                "merchantId" : 2,
     *                "mallId" : 1,
     *                "status" : "S2_SELLING"
     *                "masterPacketProduct" : [
     *                      "productId" : 23,
     *                      "name" : "牛奶",
     *                      "merchantName" : "大口九",
     *                      "sellPrice" : 234,
     *                      "packetPrice" : 234,
     *                      "useNumber" : 3,
     *                      "quantity" : 333,
     *                      "resellFee" : 23,
     *                      "marketId" : 23,
     *                      "marketMerchantId" : 23,
     *                      "logoUrl" : /3223234/324.jpg
     *                ],
     *                "collocationPacketProductList" : [
     *                      {
     *                          "productId" : 23,
     *                          "name" : "牛奶",
     *                          "merchantName" : "大口九",
     *                          "sellPrice" : 234,
     *                          "packetPrice" : 233,
     *                          "useNumber" : 1,
     *                          "quantity" : 222,
     *                          "resellFee" : 4,
     *                          "marketId" : 4,
     *                          "marketMerchantId" : 4,
     *                          "logoUrl" : /3223234/324.jpg
     *                      },
     *                      ......
     *                ],
     *                "merchantPacketCouponList" : [
     *                  {
     *                  "couponId": 20,
     *                  "name": "傻了么",
     *                  "useScope": "ALL_STORE",
     *                  "type": "VOUCHERS",
     *                  "merchantName": "b1测试商户 X",
     *                  "leaveTotal": 6,
     *                   "useNumber" : 3,
     *                  "introduction": "满享7折",
     *                  "logoUrl" : /3223234/324.jpg
     *                  },
     *                     ......
     *                ]
     *            }
     *     ]
     * }
     *
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_INFO, method = RequestMethod.GET)
    public JsonResult giftPacketInfo(HttpServletRequest request, GiftPacketDto giftPacketDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (giftPacketDto.getId() == null) {
                jsonResult.remind(MerchantGiftPacket.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MerchantGiftPacket giftPacket = new MerchantGiftPacket();
            if (StringUtils.isBlank(giftPacketDto.getGiftPacketInfoLink())) {
                giftPacket = merchantGiftPacketRepository.findByIdAndMerchantId(giftPacketDto.getId(), userInfoDto.merchant.getId());
            } else {
                giftPacket = merchantGiftPacketRepository.findOne(giftPacketDto.getId());
            }

            if (giftPacket == null) {
                jsonResult.remind(MerchantGiftPacket.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            RBeanUtils.copyProperties(giftPacket, giftPacketDto);
            giftPacketDto.setShareFee(Double.valueOf(giftPacket.getShareFee().toString()));
            giftPacketDto.setSellPrice(Double.valueOf(giftPacket.getSellPrice().toString()));
            giftPacketDto.setBasePrice(Double.valueOf(giftPacket.getBasePrice().toString()));
            giftPacketDto.setStatus(giftPacket.getStatus().toString());
            List<MerchantGiftPacketProductDto> masterProduct = merchantGiftPacketRepository.findGiftPacketProduct(giftPacket.getId(), GiftPacketProductType.MASTER);
            if (masterProduct.size() > 0) {
                giftPacketDto.setMasterPacketProduct(masterProduct.get(0));
            }
            giftPacketDto.setMasterPacketProduct(masterProduct.get(0));
            List<MerchantGiftPacketProductDto> collocationProduct = merchantGiftPacketRepository.findGiftPacketProduct(giftPacket.getId(), GiftPacketProductType.COLLOCATION);
            giftPacketDto.setCollocationPacketProductList(collocationProduct);
            List<MerchantGiftPacketCouponDto> merchantCoupon = merchantGiftPacketRepository.findMerchantCouponList(giftPacket.getId());
            giftPacketDto.setMerchantPacketCouponList(merchantCoupon);

            jsonResult.data = giftPacketDto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /merchant/gift/packet/save 产品礼包 保存
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} name <code>必须参数</code> 礼包标题
     * @apiParam {String} coverUrl <code>必须参数</code> 礼包广告图
     * @apiParam {Long} masterPacketProduct_productId <code>必须参数</code> 礼包主产品ID
     * @apiParam {BigDecimal} masterPacketProduct_packetPrice <code>必须参数</code> 礼包主产品单价
     * @apiParam {Long} masterPacketProduct_useNumber <code>必须参数</code> 礼包主产品使用数量
     * @apiParam {Long} masterPacketProduct_merchantId <code>必须参数</code> 礼包主产品商家ID
     * @apiParam {Long} masterPacketProduct_marketId 礼包主产品属于分销产品唯一标志
     * @apiParam {Date} dateEnabled <code>必须参数</code> 礼包开始时间
     * @apiParam {Date} dateDisabled <code>必须参数</code> 礼包结束时间
     * @apiParam {BigDecimal} basePrice <code>必须参数</code> 总价
     * @apiParam {String==S1_DRAFTED("草稿"), S2_SELLING("发布")} status <code>必须参数</code> 礼包状态
     * @apiParam {BigDecimal} sellPrice <code>必须参数</code> 礼包价
     * @apiParam {String} intro 礼包介绍
     * @apiParam {Long} collocationPacketProductList_productId 搭配产品ID
     * @apiParam {BigDecimal} collocationPacketProductList_packetPrice 搭配产品单价
     * @apiParam {Long} collocationPacketProductList_useNumber 搭配产品使用数量
     * @apiParam {Long} collocationPacketProductList_merchantId 搭配产品商家id
     * @apiParam {Long} collocationPacketProductList_marketId 礼包主产品属于分销产品唯一标志
     * @apiParam {Long} merchantPacketCouponList_couponId 卡卷ID
     * @apiParam {Long} merchantPacketCouponList_useNumber 卡卷使用数量
     * @apiParam {Long} merchantPacketCouponList_merchantId 卡卷商家ID
     * @apiParam {String} shareFee 分享返利
     * @apiParam {String} recommend <code>必须参数</code> 是否共享营销 默认false
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "5".
     *     "desc" : "成功",
     *     "data" : []
     * }
     *
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_SAVE, method = RequestMethod.POST)
    public JsonResult giftPacketSave(HttpServletRequest request, @RequestBody GiftPacketDto giftPacketDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing;
        doing = jsonResult -> {
            if (StringUtils.isNotBlank(giftPacketDto.getStatus()) && !EnumUtils.isValidEnum(GiftPacketStatus.class, giftPacketDto.getStatus())) {
                jsonResult.remind("礼包状态 S1_DRAFTED(\"草稿\"), S2_SELLING(\"发布\")", log);
                return;
            }
            if (StringUtils.isBlank(giftPacketDto.getName())) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_NAME_IS_NOT_NULL, log);
                return;
            }
            if (StringUtils.isBlank(giftPacketDto.getCoverUrl())) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_COVER_URL_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getDateEnabled() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_DATE_ENABLE_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getDateDisabled() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_DATE_DISABLE_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getMasterPacketProduct() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_MASTER_PRODUCT_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getBasePrice() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_BASE_PRICE_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getSellPrice() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_SELL_PRICE_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getRecommend() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_RECOMMEND_IS_NOT_NULL, log);
                return;
            }

            Product masterProduct = merchantProductRepository.findOne(giftPacketDto.getMasterPacketProduct().getProductId());
            if (masterProduct == null) {
                jsonResult.remind("您好,您所选的主产品不存在",log);
                return;
            }

            Map<Long, String> mapCoupon = giftPacketHelper.checkCoupon(giftPacketDto.getMerchantPacketCouponList());
            if (!mapCoupon.isEmpty()) {
                jsonResult.custom("8", "礼包含有赠送卡卷的库存不足", log);
                jsonResult.data = mapCoupon;
                return;
            }
            Map<String, Map<Long, String>> mapProduct = giftPacketHelper.checkProduct(masterProduct, giftPacketDto.getMasterPacketProduct(), giftPacketDto.getCollocationPacketProductList());

            if (!mapProduct.get("quantity").isEmpty()) {
                jsonResult.custom("7", "礼包含有产品的库存不足", log);
                jsonResult.data = mapProduct.get("quantity");
                return;
            }
            if (!mapProduct.get("mapStatus").isEmpty()) {
                jsonResult.custom("9", "礼包含有产品不处于出售中", log);
                jsonResult.data = mapProduct.get("mapStatus");
                return;
            }

            MarketMerchantGiftPacket marketMerchantGiftPacket = new MarketMerchantGiftPacket();
            if (giftPacketDto.getRecommend()) {
                if (!mapProduct.get("fee").isEmpty()) {
                    jsonResult.custom("5", "礼包含有不设置佣金的产品,不能加入礼包分销", log);
                    jsonResult.data = mapProduct.get("fee");
                    return;
                }
                if (!mapProduct.get("audit").isEmpty()) {
                    jsonResult.custom("6", "礼包含有需要审核的分销产品,不能加入礼包分销", log);
                    jsonResult.data = mapProduct.get("audit");
                    return;
                }
                marketMerchantGiftPacket.setRecommend(true);
            }

            if (giftPacketDto.getDateEnabled() != null) {
                if (giftPacketDto.getDateEnabled().getTime() > new Date().getTime() && GiftPacketStatus.S2_SELLING == GiftPacketStatus.valueOf(giftPacketDto.getStatus())) {
                    giftPacketDto.setStatus(GiftPacketStatus.S6_UNSTART.toString());
                }
            }

            MerchantGiftPacket giftPacket = new MerchantGiftPacket();
            giftPacket.setName(giftPacketDto.getName());
            giftPacket.setBasePrice(new BigDecimal(giftPacketDto.getBasePrice()));
            giftPacket.setCoverUrl(giftPacketDto.getCoverUrl());
            giftPacket.setDateDisabled(giftPacketDto.getDateDisabled());
            giftPacket.setDateEnabled(giftPacketDto.getDateEnabled());
            giftPacket.setIntro(giftPacketDto.getIntro());
            giftPacket.setMallId(userInfoDto.mall.getId());
            giftPacket.setMerchantId(userInfoDto.merchant.getId());
            giftPacket.setRecommend(giftPacketDto.getRecommend());
            giftPacket.setShareFee(new BigDecimal(giftPacketDto.getShareFee()));
            giftPacket.setSellPrice(new BigDecimal(giftPacketDto.getSellPrice()));
            giftPacket.setStatus(GiftPacketStatus.valueOf(giftPacketDto.getStatus()));//礼包状态
            giftPacket.setMerchantName(userInfoDto.merchant.getName());
            giftPacket.setResellFee(new BigDecimal(mapProduct.get("resellFee").get(0L).toString()));
            final MerchantGiftPacket finalGiftPacket = merchantGiftPacketRepository.save(giftPacket);

            if (giftPacketDto.getRecommend() && GiftPacketStatus.S2_SELLING == GiftPacketStatus.valueOf(giftPacketDto.getStatus())) {
                marketMerchantGiftPacket.setPacketId(finalGiftPacket.getId());
                marketMerchantGiftPacket.setMallId(finalGiftPacket.getMallId());
                marketMerchantGiftPacket.setMerchantId(finalGiftPacket.getMerchantId());
                marketMerchantGiftPacketRepository.save(marketMerchantGiftPacket);
            }

            final Long supplierMerchantId = userInfoDto.merchant.getId();

            //添加合作关系
            MarketMerchantCooperation marketMerchantCooperation = null;
            Long masterSupplierMerchantId = giftPacketDto.getMasterPacketProduct().getMerchantId();
            if (giftPacketDto.getMasterPacketProduct().getMarketId() != null) {
                masterSupplierMerchantId = giftPacketDto.getMasterPacketProduct().getMarketMerchantId();
            }
            marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(masterSupplierMerchantId, userInfoDto.merchant.getId(), MarketMerchantCooperationStatus.REFUSE);
            if (marketMerchantCooperation == null && !Objects.equals(masterSupplierMerchantId, supplierMerchantId)) {
                giftPacketHelper.saveMarketMerchantCooperation(userInfoDto, masterSupplierMerchantId);
            }
            if (giftPacketDto.getCollocationPacketProductList() != null && giftPacketDto.getCollocationPacketProductList().size() > 0) {
                for (MerchantGiftPacketProductDto ignored : giftPacketDto.getCollocationPacketProductList()) {
                    Long collocationSupplierMerchantId = ignored.getMerchantId();
                    if (ignored.getMarketMerchantId() != null) {
                        collocationSupplierMerchantId = ignored.getMarketMerchantId();
                    }
                    marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(collocationSupplierMerchantId, userInfoDto.merchant.getId(), MarketMerchantCooperationStatus.REFUSE);
                    if (!Objects.equals(masterSupplierMerchantId, collocationSupplierMerchantId) && marketMerchantCooperation == null) {
                        giftPacketHelper.saveMarketMerchantCooperation(userInfoDto, collocationSupplierMerchantId);
                    }
                }
            }

            //判断产品是否是自己产品(自己分销产品)    主产品
            Product selfProduct = giftPacketHelper.isSelfProduct(userInfoDto, giftPacketDto.getMasterPacketProduct());
            if (selfProduct != null) {
                giftPacketDto.getMasterPacketProduct().setProductId(selfProduct.getId());
                if (selfProduct.getMarketId() != null) {
                    giftPacketDto.getMasterPacketProduct().setMarketId(selfProduct.getMarketId());
                    giftPacketDto.getMasterPacketProduct().setMarketMerchantId(selfProduct.getMarketMerchantId());
                }
            }

            //产品设置
            //主产品
            giftPacketHelper.saveMerchantGiftPacketProduct(finalGiftPacket.getId(), giftPacketDto.getMasterPacketProduct(), GiftPacketProductType.MASTER);
            //搭配产品
            if (giftPacketDto.getCollocationPacketProductList() != null && giftPacketDto.getCollocationPacketProductList().size() > 0) {
                for (MerchantGiftPacketProductDto productStr : giftPacketDto.getCollocationPacketProductList()) {
                    //判断产品是否是自己产品(自己分销产品)    搭配产品
                    selfProduct = giftPacketHelper.isSelfProduct(userInfoDto, productStr);
                    if (selfProduct != null) {
                        productStr.setProductId(selfProduct.getId());
                        if (selfProduct.getMarketId() != null) {
                            productStr.setMarketId(selfProduct.getMarketId());
                            productStr.setMarketMerchantId(selfProduct.getMarketMerchantId());
                        }
                    }
                    giftPacketHelper.saveMerchantGiftPacketProduct(finalGiftPacket.getId(), productStr, GiftPacketProductType.COLLOCATION);
                }
            }
            //卡卷设置
            if (giftPacketDto.getMerchantPacketCouponList() != null && giftPacketDto.getMerchantPacketCouponList().size() > 0) {
                for (MerchantGiftPacketCouponDto couponStr : giftPacketDto.getMerchantPacketCouponList()) {
                    giftPacketHelper.saveMerchantGiftPacketCoupon(finalGiftPacket.getId(), couponStr);
                }
            }
        };
        return doing.go(giftPacketDto, userInfoDto, request, objectMapper, log);
    }

    /**
     * @api {post} /merchant/gift/packet/update 产品礼包 更改
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必须参数</code> 礼包ID
     * @apiParam {String} name <code>必须参数</code> 礼包标题
     * @apiParam {String} coverUrl <code>必须参数</code> 礼包广告图
     * @apiParam {Long} masterPacketProduct_productId <code>必须参数</code> 礼包主产品ID
     * @apiParam {BigDecimal} masterPacketProduct_packetPrice <code>必须参数</code> 礼包主产品单价
     * @apiParam {Long} masterPacketProduct_useNumber <code>必须参数</code> 礼包主产品使用数量
     * @apiParam {Long} masterPacketProduct_merchantId <code>必须参数</code> 礼包主产品商家ID
     * @apiParam {Date} dateEnabled <code>必须参数</code> 礼包开始时间
     * @apiParam {Date} dateDisabled <code>必须参数</code> 礼包结束时间
     * @apiParam {BigDecimal} basePrice <code>必须参数</code> 总价
     * @apiParam {BigDecimal} sellPrice <code>必须参数</code> 礼包价
     * @apiParam {String==S1_DRAFTED("草稿"), S2_SELLING("发布")} status <code>必须参数</code> 礼包状态
     * @apiParam {String} intro 礼包介绍
     * @apiParam {Long} collocationPacketProductList_productId 搭配产品ID
     * @apiParam {BigDecimal} collocationPacketProductList_packetPrice 搭配产品单价
     * @apiParam {Long} collocationPacketProductList_useNumber 搭配产品使用数量
     * @apiParam {Long} collocationPacketProductList_merchantId 搭配产品商家ID
     * @apiParam {Long} merchantPacketCouponList_couponId 卡卷ID
     * @apiParam {Long} merchantPacketCouponList_useNumber 卡卷使用数量
     * @apiParam {Long} merchantPacketCouponList_merchantId 卡卷商家ID
     * @apiParam {String} shareFee 分享返利
     * @apiParam {String} recommend <code>必须参数</code> 是否共享营销 默认false
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1"
     *     "desc" : "成功"
     * }
     *
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_UPDATE, method = RequestMethod.POST)
    public JsonResult giftPacketUpdate(HttpServletRequest request, @RequestBody GiftPacketDto giftPacketDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (giftPacketDto.getId() == null) {
                jsonResult.remind(MerchantGiftPacket.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MerchantGiftPacket giftPacket = merchantGiftPacketRepository.findByIdAndMerchantId(giftPacketDto.getId(), userInfoDto.merchant.getId());
            if (giftPacket == null) {
                jsonResult.remind(MerchantGiftPacket.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }

            if (StringUtils.isNotBlank(giftPacketDto.getName())) {
                giftPacket.setName(giftPacketDto.getName());
            }
            if (StringUtils.isNotBlank(giftPacketDto.getCoverUrl())) {
                giftPacket.setCoverUrl(giftPacketDto.getCoverUrl());
            }
            if (giftPacketDto.getDateEnabled() != null) {
                giftPacket.setDateEnabled(giftPacketDto.getDateEnabled());
            }
            if (giftPacketDto.getDateDisabled() != null) {
                giftPacket.setDateDisabled(giftPacketDto.getDateDisabled());
            }
            if (giftPacketDto.getMasterPacketProduct() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_MASTER_PRODUCT_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getBasePrice() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_BASE_PRICE_IS_NOT_NULL, log);
                return;
            }
            if (giftPacketDto.getSellPrice() == null) {
                jsonResult.errorParam(MerchantGiftPacket.CHECK_SELL_PRICE_IS_NOT_NULL, log);
                return;
            }

            if (giftPacketDto.getDateEnabled() != null) {
                if (giftPacketDto.getDateEnabled().getTime() < new Date().getTime() && GiftPacketStatus.S6_UNSTART == GiftPacketStatus.valueOf(giftPacketDto.getStatus())) {
                    giftPacketDto.setStatus(GiftPacketStatus.S2_SELLING.toString());
                }
                if (giftPacketDto.getDateEnabled().getTime() > new Date().getTime() && GiftPacketStatus.S2_SELLING == GiftPacketStatus.valueOf(giftPacketDto.getStatus())) {
                    giftPacketDto.setStatus(GiftPacketStatus.S6_UNSTART.toString());
                }
            }

            Product masterProduct = merchantProductRepository.findOne(giftPacketDto.getMasterPacketProduct().getProductId());
            if (masterProduct == null) {
                jsonResult.remind("您好,您所选的主产品不存在",log);
                return;
            }

            MarketMerchantGiftPacket marketMerchantGiftPacket =  marketMerchantGiftPacketRepository.findByPacketIdAndMerchantId(giftPacket.getId(), userInfoDto.merchant.getId());
            Map<Long, String> mapCoupon = giftPacketHelper.checkCoupon(giftPacketDto.getMerchantPacketCouponList());
            if (!mapCoupon.isEmpty()) {
                jsonResult.custom("8", "礼包含有赠送卡卷的库存不足", log);
                jsonResult.data = mapCoupon;
                return;
            }
            Map<String, Map<Long, String>> mapProduct = giftPacketHelper.checkProduct(masterProduct, giftPacketDto.getMasterPacketProduct(), giftPacketDto.getCollocationPacketProductList());

            if (!mapProduct.get("quantity").isEmpty()) {
                jsonResult.custom("7", "礼包含有产品的库存不足", log);
                jsonResult.data = mapProduct.get("quantity");
                return;
            }
            if (!mapProduct.get("mapStatus").isEmpty()) {
                jsonResult.custom("9", "礼包含有产品不处于出售中", log);
                jsonResult.data = mapProduct.get("mapStatus");
                return;
            }
            if (giftPacketDto.getRecommend()) {
                if (!mapProduct.get("fee").isEmpty()) {
                    jsonResult.custom("5", "礼包含有不设置佣金的产品,不能加入礼包分销", log);
                    jsonResult.data = mapProduct.get("fee");
                    return;
                }
                if (!mapProduct.get("audit").isEmpty()) {
                    jsonResult.custom("6", "礼包含有需要审核的分销产品,不能加入礼包分销", log);
                    jsonResult.data = mapProduct.get("audit");
                    return;
                }

                if (marketMerchantGiftPacket == null){
                    marketMerchantGiftPacket = new MarketMerchantGiftPacket();
                }
                marketMerchantGiftPacket.setRecommend(true);
                marketMerchantGiftPacket.setMerchantId(userInfoDto.merchant.getId());
                marketMerchantGiftPacket.setMallId(userInfoDto.mall.getId());
                marketMerchantGiftPacket.setPacketId(giftPacketDto.getId());
                marketMerchantGiftPacketRepository.save(marketMerchantGiftPacket);
            } else {
                if (marketMerchantGiftPacket != null) {
                    marketMerchantGiftPacket.setRecommend(false);
                    marketMerchantGiftPacketRepository.save(marketMerchantGiftPacket);
                }
            }
            giftPacket.setBasePrice(new BigDecimal(giftPacketDto.getBasePrice()));
            giftPacket.setIntro(giftPacketDto.getIntro());
            giftPacket.setMallId(giftPacket.getMallId());
            giftPacket.setMerchantId(giftPacket.getMerchantId());
            giftPacket.setRecommend(giftPacketDto.getRecommend());
            giftPacket.setShareFee(new BigDecimal(giftPacketDto.getShareFee()));
            giftPacket.setSellPrice(new BigDecimal(giftPacketDto.getSellPrice()));
            giftPacket.setStatus(GiftPacketStatus.valueOf(giftPacketDto.getStatus()));//礼包状态
            giftPacket.setMerchantName(userInfoDto.merchant.getName());
            giftPacket.setResellFee(new BigDecimal(mapProduct.get("resellFee").get(0L).toString()));
            final MerchantGiftPacket finalGiftPacket = merchantGiftPacketRepository.save(giftPacket);

            final Long supplierMerchantId = userInfoDto.merchant.getId();
            //添加合作关系
            MarketMerchantCooperation marketMerchantCooperation = null;
            Long masterSupplierMerchantId = giftPacketDto.getMasterPacketProduct().getMerchantId();
            if (giftPacketDto.getMasterPacketProduct().getMarketId() != null) {
                masterSupplierMerchantId = giftPacketDto.getMasterPacketProduct().getMarketMerchantId();
            }
            marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(masterSupplierMerchantId, userInfoDto.merchant.getId(), MarketMerchantCooperationStatus.REFUSE);
            if (marketMerchantCooperation == null && !Objects.equals(masterSupplierMerchantId, supplierMerchantId)) {
                giftPacketHelper.saveMarketMerchantCooperation(userInfoDto, masterSupplierMerchantId);
            }
            if (giftPacketDto.getCollocationPacketProductList() != null && giftPacketDto.getCollocationPacketProductList().size() > 0) {
                for (MerchantGiftPacketProductDto ignored : giftPacketDto.getCollocationPacketProductList()) {
                    Long collocationSupplierMerchantId = ignored.getMerchantId();
                    if (ignored.getMarketMerchantId() != null) {
                        collocationSupplierMerchantId = ignored.getMarketMerchantId();
                    }
                    if (!Objects.equals(masterSupplierMerchantId, collocationSupplierMerchantId)) {
                        marketMerchantCooperation = marketMerchantCooperationRepository.findBySupplierMerchantIdAndDistributorMerchantIdAndStatusNot(collocationSupplierMerchantId, userInfoDto.merchant.getId(), MarketMerchantCooperationStatus.REFUSE);
                        if (marketMerchantCooperation == null) {
                            giftPacketHelper.saveMarketMerchantCooperation(userInfoDto, collocationSupplierMerchantId);
                        }
                    }
                }
            }


            merchantGiftPacketProductRepository.deleteByPacketId(giftPacket.getId());
            merchantGiftPacketCouponRepository.deleteByPacketId(giftPacket.getId());

            //判断产品是否是自己产品(自己分销产品)    主产品
            Product selfProduct = giftPacketHelper.isSelfProduct(userInfoDto, giftPacketDto.getMasterPacketProduct());
            if (selfProduct != null) {
                giftPacketDto.getMasterPacketProduct().setMerchantId(selfProduct.getMerchantId());
                giftPacketDto.getMasterPacketProduct().setProductId(selfProduct.getId());
                if (selfProduct.getMarketId() != null) {
                    giftPacketDto.getMasterPacketProduct().setMarketId(selfProduct.getMarketId());
                    giftPacketDto.getMasterPacketProduct().setMarketMerchantId(selfProduct.getMarketMerchantId());
                }
            }

            //主产品
            //产品设置
            giftPacketHelper.saveMerchantGiftPacketProduct(finalGiftPacket.getId(), giftPacketDto.getMasterPacketProduct(), GiftPacketProductType.MASTER);
            //搭配产品
            if (giftPacketDto.getCollocationPacketProductList() != null && giftPacketDto.getCollocationPacketProductList().size() > 0) {
                for (MerchantGiftPacketProductDto productStr : giftPacketDto.getCollocationPacketProductList()) {
                    //判断产品是否是自己产品(自己分销产品)    搭配产品
                    selfProduct = giftPacketHelper.isSelfProduct(userInfoDto, productStr);
                    if (selfProduct != null) {
                        productStr.setProductId(selfProduct.getId());
                        productStr.setMerchantId(selfProduct.getMerchantId());
                        if (selfProduct.getMarketId() != null) {
                            productStr.setMarketId(selfProduct.getMarketId());
                            productStr.setMarketMerchantId(selfProduct.getMarketMerchantId());
                        }
                    }
                    giftPacketHelper.saveMerchantGiftPacketProduct(finalGiftPacket.getId(), productStr, GiftPacketProductType.COLLOCATION);
                }
            }
            //卡卷设置
            if (giftPacketDto.getMerchantPacketCouponList() != null && giftPacketDto.getMerchantPacketCouponList().size() > 0) {
                for (MerchantGiftPacketCouponDto couponStr : giftPacketDto.getMerchantPacketCouponList()) {
                    giftPacketHelper.saveMerchantGiftPacketCoupon(finalGiftPacket.getId(), couponStr);
                }
            }

        };
        return doing.go(giftPacketDto, userInfoDto, request, objectMapper, log);
    }

    /**
     * @api {put} /merchant/validate/gift/packet/product 产品礼包 校验加入礼包产品
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} masterProductId 主产品ID
     * @apiParam {List} collocationProductIds 搭配ID
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1".
     *     "desc" : "成功"
     * }
     *
     */
    @RequestMapping(value = Routes.VALIDATE_GIFT_PACKET_PRODUCT, method = RequestMethod.PUT)
    public JsonResult validateGiftPacketProduct(HttpServletRequest request, @RequestBody  GiftPacketDto giftPacketDto){
        RestDoing doing = jsonResult -> {
            if (giftPacketDto.getMasterProductId() == null) {
                jsonResult.remind(Product.CHECK_MASTER_PRODUCT_ID_IS_NOT_NULL,log);
                return;
            }
            Map<Long, String> mapFee = new HashedMap();
            Map<Long, String> mapAudit = new HashedMap();
            Product masterProduct = merchantProductRepository.findOne(giftPacketDto.getMasterProductId());
            if (masterProduct == null) {
                jsonResult.remind("您好,您所选的主产品不存在",log);
                return;
            }
            if (Double.valueOf(masterProduct.getResellFee().toString()) == 0D) {
                mapFee.put(masterProduct.getId(), masterProduct.getName());
            }
            if (masterProduct.getMarketId() != null) {
                Merchant merchant = merchantRepository.findOne(masterProduct.getMarketMerchantId());
                if (merchant.getProdAudit()) {
                    mapAudit.put(masterProduct.getId(), masterProduct.getName());
                }
            }
            //礼包共享营销校验(搭配产品)
            if (giftPacketDto.getCollocationProductIds().size() > 0) {
                List<Product> productList = merchantProductRepository.findByIdIn(giftPacketDto.getCollocationProductIds());
                for (Product product : productList) {
                    if (Double.valueOf(product.getResellFee().toString()) == 0D ) {
                        mapFee.put(product.getId(), product.getName());
                    }
                    if (product.getMarketId() != null) {
                        Merchant merchant = merchantRepository.findOne(product.getMarketMerchantId());
                        if (merchant.getProdAudit()) {
                            mapAudit.put(product.getId(), product.getName());
                        }
                    }
                }
            }
            if (!mapFee.isEmpty()) {
                jsonResult.custom("5", "礼包含有不设置佣金的产品,不能加入礼包分销", log);
                jsonResult.data = mapFee;
                return;
            }
            if (!mapAudit.isEmpty()) {
                jsonResult.custom("6", "礼包含有需要审核的分销产品,不能加入礼包分销", log);
                jsonResult.data = mapAudit;
                return;
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/gift/packet/product/page 产品礼包 筛选我的产品分页
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=ASC("升序"), DESC("降序")} sort 排序(sortByName为空则sort为空,sortByName传值则sort传值)
     * @apiParam {String=last_updated("发布时间"), quantity("库存")} sortByName 按字段排序
     * @apiParam {String} keyword 产品编号/名称/商家名称
     * @apiParam {String=SERVICE("服务"), GOODS("商品"), ALL("全部")} type <code>必须参数</code> 产品类型 默认 ALL
     * @apiParam {Integer=SELF("自营"), MARKET("分销"), ALL("全部")} productSourceType <code>必须参数</code>  产品来源 默认 ALL
     * @apiParam {String} categoryId 品类 默认全部传空, 其他情况传值调/market/merchant/product/category 返回ID值
     * @apiParam {String} maxPrice 最大售价 默认全部传空
     * @apiParam {String} minPrice 最小售价 默认全部传空
     * @apiParam {Long} productId 主产品ID 默认全部传空
     * @apiParam {Date} dateEnabled <code>必须参数</code> 礼包开始时间
     * @apiParam {Date} dateDisabled <code>必须参数</code> 礼包结束时间
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} marketId 分销产品唯一的识别码
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} resellFee 分销佣金
     * @apiSuccess {Long} categoryId 品类ID
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "id": 71,
     *      "type": "GOODS",
     *      "name": "宇宙",
     *      "sellPrice": 100,
     *      "quantity": 998,
     *      "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *      "mallId": 1,
     *      "merchantId": 1,
     *      "resellFee": 5,
     *      "marketId": 232,
     *      "categoryId": 232,
     *  },
     *  .....
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_PRODUCT_PAGE, method = RequestMethod.GET)
    public JsonResult giftPacketProductPage(HttpServletRequest request, ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(productDto.getProductSourceType())) {
                jsonResult.errorParam("产品来源 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(productDto.getType())) {
                jsonResult.errorParam(Product.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }

            if (productDto.getDateEnabled() == null) {
                jsonResult.remind("日期格式不正确,允许格式:" + RDateUtils.parsePattern,log);
                return;
            }

            if (productDto.getDateDisabled() == null) {
                jsonResult.remind("日期格式不正确,允许格式:" + RDateUtils.parsePattern,log);
                return;
            }

            //分类不为空
            List<Long> categoryIds = new ArrayList<>();
            if (productDto.getCategoryId() != null) {
                categoryIds = categoryHelper.categoryIds(userInfoDto.mall.getId(), Arrays.asList(productDto.getCategoryId()), null);
                if (categoryIds.size() == 0) {
                    categoryIds.add(productDto.getCategoryId());
                }
            }
            PageResult<ProductDto> pageResult = merchantProductRepository.findGiftPacketProductPage(userInfoDto.merchant.getId(), productDto.getProductId(), productDto.getType(), productDto.getProductSourceType(), productDto.getSort(), productDto.getSortByName(), productDto.getKeyword(), productDto.getDateEnabled(), productDto.getDateDisabled(), productDto.getMaxPrice(), productDto.getMinPrice(), categoryIds, this.getPage(productDto.getPageNo(), productDto.getPageSize()));
            if (productDto.getCategoryId() != null) {
                pageResult.data.stream().map(product -> {
                    product.setCategoryId(productDto.getCategoryId());
                    return product;
                }).collect(Collectors.toList());
            }else {
                pageResult.data.stream().map(product -> {
                    Long productId = product.getId();
                    if (product.getMarketId() != null) {
                        productId = product.getMarketId();
                    }
                    List<ProductCategories> productCategories = merchantProductCategoriesRepository.findByProductId(productId);
                    if (productCategories.size() > 0) {
                        product.setCategoryId(productCategories.get(0).getCategoryId());
                        Category category = categoryRepository.findByIdAndMallId(productCategories.get(0).getCategoryId(), userInfoDto.mall.getId());
                        if (category != null) {
                            product.setCategoryId(category.getParentId());
                            Category parentCategory = categoryRepository.findByIdAndMallId(category.getParentId(), userInfoDto.mall.getId());
                            if (parentCategory != null) {
                                product.setCategoryId(parentCategory.getParentId());
                            }
                        }
                    }
                    return product;
                }).collect(Collectors.toList());
            }
            pageResult.setUrl(Routes.MERCHANT_GIFT_PACKET_PRODUCT_PAGE);
            jsonResult.data = pageResult;

        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/gift/packet/market_product/page 产品礼包 筛选分销市场产品分页
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String=ASC("升序"), DESC("降序")} sort 排序(sortByName为空则sort为空,sortByName传值则sort传值)
     * @apiParam {String=resell_fee("佣金"), quantity("库存")} sortByName 按字段排序
     * @apiParam {String} keyword 产品编号/名称/商家名称
     * @apiParam {String=SERVICE("服务"), GOODS("商品"), ALL("全部")} type <code>必须参数</code> 产品类型 默认 ALL
     * @apiParam {String} categoryId 品类 默认全部传空, 其他情况传值调/market/merchant/product/category 返回ID值
     * @apiParam {String} maxPrice 最大售价 默认全部传空
     * @apiParam {String} minPrice 最小售价 默认全部传空
     * @apiParam {Long} productId 主产品ID 默认全部传空
     * @apiParam {Date} dateEnabled <code>必须参数</code> 礼包开始时间
     * @apiParam {Date} dateDisabled <code>必须参数</code> 礼包结束时间
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} marketId 分销产品唯一的识别码
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} resellFee 分销佣金
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "id": 71,
     *      "type": "GOODS",
     *      "name": "宇宙",
     *      "sellPrice": 100,
     *      "quantity": 998,
     *      "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *      "mallId": 1,
     *      "merchantId": 1,
     *      "resellFee": 5,
     *      "marketId": 232,
     *  },
     *  ......
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_MARKET_PRODUCT_PAGE, method = RequestMethod.GET)
    public JsonResult giftPacketMarketProductPage(HttpServletRequest request, ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(productDto.getType())) {
                jsonResult.errorParam(Product.CHECK_TYPE_IS_NOT_NULL,log);
                return;
            }


            if (productDto.getDateEnabled() == null) {
                jsonResult.remind("日期格式不正确,允许格式:" + RDateUtils.parsePattern,log);
                return;
            }

            if (productDto.getDateDisabled() == null) {
                jsonResult.remind("日期格式不正确,允许格式:" + RDateUtils.parsePattern,log);
                return;
            }

            //分类不为空
            List<Long> categoryIds = new ArrayList<>();
            if (productDto.getCategoryId() != null) {
                categoryIds = categoryHelper.categoryIds(userInfoDto.mall.getId(), Arrays.asList(productDto.getCategoryId()), null);
                if (categoryIds.size() == 0) {
                    categoryIds.add(productDto.getCategoryId());
                }
            }
            PageResult<ProductDto> pageResult = merchantProductRepository.findGiftPacketMarketProductPage(userInfoDto.merchant.getId(), userInfoDto.mall.getId(), productDto.getProductId(), productDto.getType(), productDto.getSort(),
                        productDto.getSortByName(), productDto.getKeyword(), productDto.getDateEnabled(), productDto.getDateDisabled(), productDto.getMaxPrice(), productDto.getMinPrice(), categoryIds, this.getPage(productDto.getPageNo(), productDto.getPageSize()));
            pageResult.setUrl(Routes.MERCHANT_GIFT_PACKET_MARKET_PRODUCT_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /merchant/gift/packet/calculate_share_fee 产品礼包计算分享返利
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} masterProductId <code>必须参数</code> 礼包主产品ID
     * @apiParam {List} collocationProductIds 搭配产品ids
     *
     * @apiSuccessExample {json} Response
     * {
     *     "code" : "1".
     *     "desc" : "成功"
     * }
     *
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_CALCULATE_SHARE_FEE, method = RequestMethod.PUT)
    public JsonResult calculatorShareFee(HttpServletRequest request, @RequestBody  GiftPacketDto giftPacketDto){
        RestDoing doing = jsonResult -> {
            if (giftPacketDto.getMasterProductId() == null) {
                jsonResult.remind(Product.CHECK_MASTER_PRODUCT_ID_IS_NOT_NULL,log);
                return;
            }
            BigDecimal marketProduct = BigDecimal.valueOf(0);
            BigDecimal selfProduct = BigDecimal.valueOf(0);
            Product masterProduct = merchantProductRepository.findOne(giftPacketDto.getMasterProductId());
            if (masterProduct.getMarketId() == null && !masterProduct.getRecommend()) {
                selfProduct = selfProduct.add(masterProduct.getSellPrice());
            }else {
                marketProduct = marketProduct.add(masterProduct.getResellFee());
            }
            if (giftPacketDto.getCollocationProductIds() != null && giftPacketDto.getCollocationProductIds().size() > 0){
                List<Product> productList = merchantProductRepository.findByIdIn(giftPacketDto.getCollocationProductIds());
                for (Product product : productList) {
                    if (product.getMarketId() == null && !product.getRecommend()) {
                        selfProduct = selfProduct.add(product.getSellPrice());
                    }else {
                        marketProduct = marketProduct.add(product.getResellFee());
                    }
                }
                selfProduct = selfProduct.multiply(BigDecimal.valueOf(0.75));
                marketProduct = marketProduct.add(selfProduct);
            }
            jsonResult.data = marketProduct;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/gift/packet/related_page 关联礼包 分页
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String=ALL("全部"), S2_SELLING("进行中"), S5_FINISHED("已失效"), S6_UNSTART("未开始")} status 礼包状态 <code>必须参数</code> 默认 ALL
     * @apiParam  {String} keyword 礼包名称/编号
     * @apiParam  {Long} relateMerchantId 搜索条件  商家ID 默认为空
     *
     * @apiSuccess {Long} id 礼包ID
     * @apiSuccess {String} name 礼包名称
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {Date} lastUpdated 更新时间
     * @apiSuccess {Date} dateEnabled 礼包开始时间
     * @apiSuccess {Date} dateDisabled 礼包结束时间
     * @apiSuccess {Long} marketPacketId 分销礼包唯一的识别码
     * @apiSuccess {String} coverUrl 广告封面
     * @apiSuccess {String} intro 礼包介绍
     * @apiSuccess {BigDecimal} shareFee 分享返利
     * @apiSuccess {BigDecimal} basePrice 总价
     * @apiSuccess {BigDecimal} sellPrice 礼包价
     * @apiSuccess {Boolean} isRecommend 是否共享营销
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {Long} mallId 商城ID
     * @apiSuccess {Long} merchantName 商城名称
     * @apiSuccess {String} saleCount 售出数
     * @apiSuccess {String} verifiedCount 核销数
     * @apiSuccess {String} promoteUrl 二维码路径
     * @apiSuccess {String=S2_SELLING("进行中"), S3_UNLOAD("已失效"), S5_FINISHED("已失效"), S6_UNSTART("未开始")} status 礼包状态
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *                "id" : 23,
     *                "name" : "组合礼包",
     *                "dateCreated" : "2016-07-22 10:49:28",
     *                "lastUpdated" : "2016-07-22 10:49:28",
     *                "dateEnabled" : "2016-07-22 10:49:28",
     *                "dateDisabled" : "2016-07-22 10:49:28",
     *                "marketPacketId" : 343,
     *                "coverUrl" : "/20160601/201606011413084VOvLKgN.jpg",
     *                "intro" : "礼包介绍",
     *                "shareFee" : 21,
     *                "basePrice" : 231,
     *                "sellPrice" : 222,
     *                "isRecommend" : true,
     *                "merchantId" : 2,
     *                "mallId" : 1,
     *                "merchantName" : "卡哇伊",
     *                "status" : "S2_SELLING",
     *                "saleCount" : "111",
     *                "verifiedCount" : "12",
     *                "promoteUrl" : "http://uploads.rockcent.com/local/gift_packet/promote/201610/19205851423d242ea35-f601-4c83-9a72-01d3e7291551giftPacketPromote.jpg"
     *            },
     *            .......
     *     ]x
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_RELATED_PAGE , method = RequestMethod.GET)
    public JsonResult relatedGiftPacket(HttpServletRequest request, GiftPacketDto giftPacketDto){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            PageResult<GiftPacketDto> pageResult = merchantGiftPacketRepository.findRelatedGiftPacket(userInfoDto.merchant.getId(), giftPacketDto.getKeyword(), giftPacketDto.getStatus(), giftPacketDto.getRelateMerchantId(), this.getPage(giftPacketDto.getPageNo(), giftPacketDto.getPageSize()));
            pageResult.data.stream().map(packet -> {
                Long saleCount = 0L;
                Long verifiedCount = 0L;
                List<MallOrder> mallOrderList = mallOrderRepository.findByGiftIdAndMallId(packet.getId(), packet.getMallId());
                for (MallOrder mallOrder : mallOrderList) {
                    if (MallOrderStatus.PAYED == mallOrder.getStatus()) {
                        saleCount++;
                    }
                    if (MallOrderStatus.FINISHED == mallOrder.getStatus()) {
                        verifiedCount++;
                    }
                }
                packet.setSaleCount(saleCount);
                packet.setVerifiedCount(verifiedCount);
                return packet;
            }).collect(Collectors.toList());
            pageResult.setUrl(Routes.MERCHANT_GIFT_PACKET_RELATED_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/gift/packet/merchant  关联礼包 全部商家列表
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiSuccess {Long} id 商家ID
     * @apiSuccess {String} name 商城名称
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code" : "1".
     *     "desc" : "成功",
     *     "data" : [
     *            {
     *                "id" : 23,
     *                "name" : "以卡农",
     *            },
     *            .......
     *     ]
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_MERCHANT , method = RequestMethod.GET)
    public JsonResult giftPacketMerchant(HttpServletRequest request){
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            List<Merchant> merchantList = merchantGiftPacketRepository.findGiftPacketMerchant(userInfoDto.mall.getId(), userInfoDto.merchant.getId());
            jsonResult.data = merchantList;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /merchant/gift/packet/promote 产品礼包 礼包管理 推广二维码
     * @apiGroup GIFT_PACKET
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {Long} id <code>必须参数</code> id
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data": {
     *      "id": 5,
     *      "path": "http://uploads.rockcent.com//dev/product/promote/20169/252115216139d57611a-353d-41e3-8e39-d52d014d6085promote.jpg"
     *  }
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MERCHANT_GIFT_PACKET_PROMOTE, method = RequestMethod.GET)
    public JsonResult promote(HttpServletRequest request, Long id) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (id == null) {
                jsonResult.errorParam(Product.CHECK_ID_IS_NOT_NULL, log);
                return;
            }
            MerchantGiftPacket giftPacket = merchantGiftPacketRepository.findByIdAndMerchantId(id, userInfoDto.merchant.getId());
            if (giftPacket == null) {
                jsonResult.remind(Product.REMIND_RECORD_IS_NOT_EXIST, log);
                return;
            }

            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if (mall == null) {
                jsonResult.remind("平台不存在,请联系开发人员",log);
                return;
            }
            String host = mall.getCustomerClientDomain();
            if (StringUtils.isBlank(host)) {
                host = mall.getMobileHostName();
            }

            StringBuffer url = new StringBuffer();
            url.append("http://").append(host)
                    .append("/wechat/giftDetail/")
                    .append(giftPacket.getId()).append("/?id=").append(giftPacket.getId());
            QrCodeDto qrCodeDto = new QrCodeDto();
            qrCodeDto.setId(userInfoDto.getId());
            qrCodeDto.setMallId(userInfoDto.mall.getId());
            qrCodeDto.setMerchantId(userInfoDto.merchant.getId());
            UploadImageFileDto uploadImageFileDto = qrCodeHelper.createQRCode(qrCodeDto, url.toString(), "giftPacketPromote.jpg", UploadFileBusinessType.GIFT_PACKET_PROMOTE, prop.env, prop.aliyunOssBucketName, prop.domainUploadsHttp);
            giftPacket.setPromoteUrl(uploadImageFileDto.getPath());
            giftPacket.setcAccessUrl(url.toString());
            merchantGiftPacketRepository.save(giftPacket);
            jsonResult.data = uploadImageFileDto;
        };
        return doing.go(request, log);
    }
}
